//获取应用实例
const app = getApp();
import Toast from '../../assets/ui/toast/toast';

const util = require('../../assets/util.js');

var socketTask;
Page({
    data: {
        list: [], //列表
        fontColor: [
            'rgb(37,141,103)',
            'rgb(220,91,174)'
        ],
        avatar: [
            '/assets/img/girl.svg',
            '/assets/img/boy.svg'
        ],
        // viewID: '', //最底部的id
        times: 0, //列表数量
        timer: 5000, //获取间隔.
        first: true,
        meetingid: null,
        editShow: false,
        contentMsg: '',
        editIndex: 0,
        editId: null,
        playTime: '00:00',
        totalTime: '--:--',
        canPlay: false,
        playBtnS: true,//true play,false pause
        playCurrentValue: 0
    },
    onLoad(option) {
        this.setData({
            meetingid: parseInt(option.id) || 3
        });
        this.getList();
        let list = app.globalData.meetingList;
        let audioItem = list.filter(item => item.id === parseInt(option.id));
        // console.log(audioItem)
        this.audioPlay = wx.createInnerAudioContext();
        //不遵循系统静音开关，即使用户打开了静音开关，也能继续发出声音
        if (wx.setInnerAudioOption) {
            wx.setInnerAudioOption({
                obeyMuteSwitch: false
            })
        } else {
            this.audioPlay.obeyMuteSwitch = false;
        }
        //监听各个阶段
        this.audioPlay.onCanplay(() => {
            console.log('可以播放');
            this.audioPlay.duration;
            setTimeout(() => {
                this.setData({
                    canPlay: true,
                    totalTime: util.secondToDate(this.audioPlay.duration)
                })
            }, 1000)
        });
        this.audioPlay.onPlay(() => {
            console.log('监听到音频开始播放');
            this.setData({
                totalTime: util.secondToDate(this.audioPlay.duration)
            })
        });
        this.audioPlay.onEnded(() => {
            console.log('音频自然播放结束事件');
            this.setData({
                playBtnS: true,
                playTime: '00:00',
                playCurrentValue: 0
            })
        });
        this.audioPlay.onStop(() => {
            console.log('音频停止事件');
        });
        this.audioPlay.onError((res) => {
            console.log(res);
            wx.showToast({
                title: '音频错误',
                icon: 'none'
            })
        });
        this.audioPlay.onTimeUpdate(res => {
            // console.log(this.audioPlay.currentTime)
            let currentTime = this.audioPlay.currentTime;
            this.setData({
                playTime: util.secondToDate(currentTime),
                playCurrentValue: currentTime / this.audioPlay.duration * 100
            })

        });
        this.audioPlay.src = audioItem[0].audiourl;
    },
    voiceTimeBar(e) {
        this.audioPlay.seek(e.detail / 100 * this.audioPlay.duration)
    },
    prevTime() {
        this.audioPlay.seek(this.audioPlay.currentTime - 5)
    },
    nextTime() {
        this.audioPlay.seek(this.audioPlay.currentTime + 5)
    },
    playOrPause() {
        if (!this.data.canPlay) return;
        if (this.audioPlay.paused) {
            this.audioPlay.play();
        } else {
            this.audioPlay.pause();
        }
        this.setData({
            playBtnS: !this.audioPlay.paused
        })
    },
    editContent(e) {
        let dataset = e.currentTarget.dataset,
            list = this.data.list;
        list.forEach((item, index) => {
            item.edit = index === dataset.index;
        });
        this.setData({
            list,
            editId: dataset.id,
            editIndex: dataset.index,
            contentMsg: list[dataset.index].textmessage,
            editShow: true
        });

    },
    inputContent(e) {
        this.setData({
            contentMsg: e.detail
        })
    },
    confirmEdit() {
        let contentMsg = this.data.contentMsg.replace(/\s+/g, "");
        this.setData({
            editShow: false
        });
        if (contentMsg === '') {
            this.cancelEdit();
            Toast('内容不能为空');
        } else {
            let that = this,
                contentMsg = that.data.contentMsg;
            wx.showLoading({
                title: `保存中...`,
            });
            wx.request({
                url: 'https://ai.iweigame.com/aiaudio/updatemsg',
                data: {
                    mid: that.data.editId,
                    textstring: contentMsg
                },
                success(res) {
                    console.log(res.data);
                    let list = that.data.list;
                    list[that.data.editIndex].textmessage = contentMsg;
                    list[that.data.editIndex].edit = false;
                    that.setData({
                        list
                    });
                    Toast.success('更新成功');
                },
                fail() {
                    Toast.fail('保存失败');
                },
                complete() {
                    wx.hideLoading()
                }
            })
        }
    },
    cancelEdit() {
        let list = this.data.list;
        list[this.data.editIndex].edit = false;
        this.setData({
            editShow: false,
            list
        })
    },
    //开始会议
    changeMeeting(e) {
        let action = e.currentTarget.dataset.action;
        wx.showLoading({
            title: `正在${action === 'start' ? '开始' : '结束'}...`,
        });
        wx.request({
            url: 'https://ai.iweigame.com/aiaudio/mettingstatus',
            // url: 'http://192.168.1.5:8888/aiaudio/mettingstatus',
            data: {
                status: action === 'start' ? 1 : 0,
                meetingid: this.data.meetingid
            },
            success(res) {
                console.log(res)
            },
            fail() {
                Toast.fail('操作失败');
            },
            complete() {
                wx.hideLoading()
            }
        })
    },
    onHide() {

        console.log('detail onHide');
        socketTask.close(function (close) {
            console.log('关闭 WebSocket 连接。', close)
        })

    },
    onUnload() {
        console.log('detail onUnload');
        //销毁播放器实例
        this.audioPlay.destroy();
        socketTask.close(function (close) {
            console.log('关闭 WebSocket 连接。', close)
        })
    },
    onReady() {

        let that = this;
        socketTask = wx.connectSocket({
            url: 'wss://ai.iweigame.com/websocket'
            // url: 'ws://192.168.1.5:8888/websocket'
        });
        socketTask.onOpen(res => {

            console.log('监听 WebSocket 连接打开事件。', res)
        });
        socketTask.onClose(onClose => {
            console.log('监听 WebSocket 连接关闭事件。', onClose)


        });
        socketTask.onError(onError => {
            console.log('监听 WebSocket 错误。错误信息', onError)
        });
        socketTask.onMessage(msg => {
            console.log('detail received msg: ' + res.data);
            var mycars = [{textmessage: res.data, id: Math.round(Date.now() / 10000), addtime: 1545011581686}];

            mycars.forEach(item => {
                let times = that.data.times + 1;
                item['rgb'] = times % 2 === 0 ? that.data.fontColor[0] : that.data.fontColor[1];
                item['avatar'] = times % 2 === 0 ? that.data.avatar[0] : that.data.avatar[1];
                item['username'] = '某某某';
                item['time'] = times; //保证id值唯一
                that.setData({
                    times
                })
            });
            let list = that.data.list;
            that.setData({
                list: mycars.concat(list)
            });
            console.log(list);
            console.log(mycars);
        });
        wx.onSocketOpen(function (res) {
            console.log('detail websocket opened.');
        });
        wx.onSocketError(function (res) {
            console.log('detail websocket fail');
        });
        wx.onSocketMessage(function (res) {
            // console.log('detail received msg: ' + res.data);
            // var mycars = [{ textmessage: res.data, id: Math.round(Date.now() / 10000), addtime: 1545011581686 }];

            // mycars.forEach(item => {
            //   let times = that.data.times + 1
            //   item['rgb'] = times % 2 === 0 ? that.data.fontColor[0] : that.data.fontColor[1];
            //   item['avatar'] = times % 2 === 0 ? that.data.avatar[0] : that.data.avatar[1];
            //   item['username'] = '某某某';
            //   item['time'] = times //保证id值唯一
            //   that.setData({
            //     times
            //   })
            // })
            // let list = that.data.list;
            // that.setData({
            //   list: mycars.concat(list)

            // })
            // console.log(list);
            // console.log(mycars);
        });
    },
    getList() {
        let that = this;
        if (this.data.first) {//第一次加载loading
            wx.showLoading({
                title: '加载中...',
            });
        }
        let fail = () => {
            wx.showModal({
                title: '错误',
                confirmText: '重试',
                cancelText: '返回',
                content: '获取列表失败',
                success(res) {
                    if (res.confirm) {
                        that.getList()
                    } else if (res.cancel) {
                        wx.navigateBack()
                    }
                }
            })
        };
        wx.request({
            url: 'https://ai.iweigame.com/aiaudio/getmessages',
            data: {
                lasttime: Math.round(Date.now() / 1000),
                meetingid: this.data.meetingid
            },
            success(res) {
                if (res.statusCode === 200) {
                    // 这里改成了只取十个，太多的话长列表手机顶不住
                    let newList = res.data;
                    let promiseAll = [];
                    newList.forEach(item => {
                        promiseAll.push(that.addList(item))
                    });

                } else {
                    fail()
                }
            },
            fail() {
                fail()
            },
            complete() {
                if (that.data.first) {
                    wx.hideLoading();
                    that.setData({
                        first: false
                    })
                }
            }
        })
    },
    addList(item) {
        let that = this;
        let times = that.data.times + 1;
        item['rgb'] = times % 2 === 0 ? that.data.fontColor[0] : that.data.fontColor[1];
        item['avatar'] = times % 2 === 0 ? that.data.avatar[0] : that.data.avatar[1];
        item['username'] = '某某某';
        item['edit'] = false;

        return new Promise(resolve => {
            that.setData({
                list: [item].concat(that.data.list),
                times
            }, () => {
                resolve()
            });
        })
    },
    rgb() {
        let r = Math.round(Math.random() * 255);
        let g = Math.round(Math.random() * 255);
        let b = Math.round(Math.random() * 255);
        return `rgb(${r},${g},${b})`
    },
    onShareAppMessage() {
        return {
            path: '/pages/index/index'
        }
    }
});
